// APP
// Main.html第一次点击对应Tab时候初始化页面
//if (window.plus) {
//    //ready();
//} else {
//    document.addEventListener('plusready', ready, false);
//}

// Web
$(function () {
    if (AGENT_CLIENT.WEB) {
        ready();
    } else if (AGENT_CLIENT.APP) {
        $(".main").css("padding-bottom", "2px");
    }
});

// 初始化方法
function ready() {
    var _main = $(".main");
    var _currentloginuser = getLocalStorage(STORAGE_MANAGER.user);
    var _contentheight = ($(window).height() - CONFIG_MANAGER.headerHight);

    var coinlistPage = function () {
        this.init();
    };
    coinlistPage.prototype = {
        // 初始化页面
        init: function () {
            this.loadData();
            this.bindEvent();
        },
        // 加载数据
        loadData: function () {
            this.getCoin();
            this.loadCategory();
            this.loadexchange();
            this.loadFans();
            this.loadgoods();

        },

        // 绑定事件
        bindEvent: function () {
            var model = this;
            $("#back").on("tap", function () {
                back();
            });

            // 跳转消息页
            $("#btnmsg").on("tap", function () {
                redirect("../message/messagelist.html");
            });

            // 置顶
            $("#gotop").on("tap", function () {
                _main.animate({scrollTop: '0px'}, 500);
            });

            // 滚动
            _main.scroll(this.isDisplayTopIcon);

            // 星粉秀
            $("#fanslistdiv").on("tap", "div[name=fansshow] > dl", function () {
                var id = $(this).attr("tip");
                if (id && id != "-1") {
                    redirect("coindetail.html?id=" + id);
                }
            });

            // 商品类型
            $("#goodstypetabdiv").on("tap", " li", function () {
                var tip = $(this).attr("tip");
                $(this).addClass("current");
                var windowsWidth = $(window).width();
                var pleft = $(this).offset().left;
                if (pleft > (windowsWidth / 2)) {
                    var le = pleft - (windowsWidth * 0.2);
                    $("#goodstypetabdiv").animate({scrollLeft: ($("#goodstypetabdiv").scrollLeft() + le) + 'px'}, 300);
                } else if (pleft < 0) {
                    var le = pleft - (windowsWidth * 0.2);
                    $("#goodstypetabdiv").animate({scrollLeft: ($("#goodstypetabdiv").scrollLeft() + le) + 'px'}, 300);
                }

                redirect("../goods/goodslist.html?isOnlyStarsGoods=true&catalog=" + $(this).attr("tip"));
            });

            // 星兑换
            $(".main").on("tap", "img[id^=adsF]", function () {
                var link = $(this).attr("link");
                if (link) {
                    redirect(link);
                }
            });

            // 星币范围
            $("#coinRangelist li").on("tap", function () {
                var tip = $(this).attr("tip");
                var activeli = $('#coinRangelist li[class=goldcolor]');

                activeli.removeClass("goldcolor");
                if (activeli.attr("tip") != tip) {
                    $(this).addClass("goldcolor");
                }
                model.loadgoods();
            });

            // 跳转商品详情
            $("#goodslist").on("tap", "li", function () {
                redirect("../goods/goodsdetail.html?id=" + $(this).attr("tip"));
            });

            // 金币领取页
            $("#getcoindiv").on("tap", function () {
                $(this).fadeOut(1500);
            });

            $('img.lazy').lazyload({
                placeholder: "../../images/grey.gif",
                event: "scroll",
                threshold: 100,
                failure_limit: 10
            });

            // 懒加载
            $('img.lazy').lazyload({
                placeholder: "../../images/grey.gif",
                event: "scroll",
                threshold: 100,
                container: $(".main"),
                failure_limit: 10
            });
        },

        // 领取星币
        getCoin: function () {
            if (!_currentloginuser) {
                return;
            }
            // 今日是否领取
            $.ajax({
                headers: {token: _currentloginuser.token},
                type: "GET",
                url: CONFIG_MANAGER.RequstUrl + "v1/member/coin/make/" + _currentloginuser.id + "/6"
            }).done(function (res) {
                if (!res.today_is_received) {
                    $("#getcoindiv").fadeIn(100);
                }
                // 计算宽度
                $("#coinnum").text(res.latest_payin);
                $("#tomorrow_payin").text(res.tomorrow_payin);
                $("#totalcoin").text(res.latest_coin);
                _currentloginuser["coin"] = res.last_coin;
                setLocalStorage(STORAGE_MANAGER.user, _currentloginuser);
            }).fail(function (res) {
                var response = JSON.parse(res.responseText);
                if (response.Message && response.Message.indexOf("票据") > -1) {
                    $.alert("你的帐号已经在其他地方登录", function () {
                        clearLocalStorage();
                        redirect("../account/login.html");
                        return;
                    });
                }
            }).always(function () {
                setTimeout(function () {$("#getcoindiv").fadeOut(1500);}, 3000);
            });
        },

        // 获取分类
        loadCategory: function () {
            var model = this;
            // 读取缓存(1天有效)
            var nowtime = new Date(new Date().Format("yyyy-MM-dd")).getTime();
            var categorycachedata = getLocalStorage(STORAGE_MANAGER.parentcategory);
            if (categorycachedata && categorycachedata.time >= nowtime) {
                $("#goodstypetabdiv").html(categorycachedata.data);
                return;
            }

            $.ajax({
                type: "GET",
                url: CONFIG_MANAGER.RequstUrl + "v1/basic/category/child/0"
            }).done(function (res) {
                var list = res;
                model.paintPage(list);
                setLocalStorage(STORAGE_MANAGER.parentcategory, {time: nowtime, data: $("#goodstypetabdiv").html()});
            });
        },

        // 画页面
        paintPage: function (list) {
            var html = [];
            $.each(list, function (i, item) {
                html.push(" <li tip='" + item.code + "'>" + item.name + "</li>");
            });
            $("#goodstypetab").html(html.join(""));

            // 计算Tab宽度
            var goodstypetabWidth = 0;
            $("#goodstypetab li").each(function () {
                goodstypetabWidth = goodstypetabWidth + ($(this).width() + 25);
            });
            $("#goodstypetab").width(goodstypetabWidth + 10);
        },

        // 星兑换
        loadexchange: function () {
            var model = this;
            var nowtime = new Date(new Date().Format("yyyy-MM-dd")).getTime();
            var adslocatins = getLocalStorage(STORAGE_MANAGER.coinadslocatins);
            if (adslocatins && adslocatins.time >= nowtime) {
                this.setAdsImg(adslocatins.data);
                return;
            }

            $.ajax({
                type: "GET",
                url: CONFIG_MANAGER.RequstUrl + "v1/ads/locatins/[APP-Coin]"
            }).done(function (res) {
                if (res) {
                    model.setAdsImg(res);
                    setLocalStorage(STORAGE_MANAGER.coinadslocatins, {time: nowtime, data: res});
                }
            });
        },

        // 设置首页广告图
        setAdsImg: function (locatins) {
            var adsimglist = $("img[id^=adsF]");
            for (var i = 0; i < adsimglist.length; i++) {
                var adsimg = $(adsimglist[i]);
                var id = adsimg.attr("id");
                var tag = id.substr(3);
                var urllist = locatins[tag];
                var imgsrc = (urllist.length > 0) ? urllist[0].path : "../../images/grey.gif";
                var imglink = (urllist.length > 0) ? urllist[0].link : "";

                // 获取图片尺寸
                var imgwidth = 114, imgheight = 114;
                var sizestr = adsimg.attr("size");
                if (sizestr) {
                    var size = sizestr.split('*');
                    if (size.length == 2) {
                        imgwidth = size[0];
                        imgheight = size[1];
                    }
                }

                adsimg.attr({"data-original": getImageUrl(imgsrc, imgwidth, imgheight), link: imglink});
            }
        },

        // 获取星粉秀
        loadFans: function () {
            var model = this;
            var newfans = $.ajax({type: "GET", url: CONFIG_MANAGER.RequstUrl + "v1/fans/rank/1/20"});
            var hotfans = $.ajax({type: "GET", url: CONFIG_MANAGER.RequstUrl + "v1/fans/rank/2/20"});
            $.when(newfans, hotfans).done(function (res1, res2) {
                model.paintFanslist(res1, res2);
            });
        },

        // 画星粉秀
        paintFanslist: function (res1, res2) {
            var newfanslist = res1[0];
            var hotfanslist = res2[0];

            var html = [];
            html.push("<h2 class='mkbiaoti'><em>星粉秀</em></h2>");

            var deffan = {id: -1, album: "../../images/grey.gif", memo: ""};
            var newfan1 = newfanslist.length > 0 ? {
                id: newfanslist[0].id,
                photo: newfanslist[0].albums && newfanslist[0].albums.length > 0 ? newfanslist[0].albums[0].photo : "",
                memo: newfanslist[0].memo
            } : deffan;

            var newfan2 = newfanslist.length > 1 ? {
                id: newfanslist[1].id,
                photo: newfanslist[1].albums && newfanslist[1].albums.length > 0 ? newfanslist[1].albums[0].photo : "",
                memo: newfanslist[1].memo
            } : deffan;
            var newfan3 = newfanslist.length > 2 ? {
                id: newfanslist[2].id,
                photo: newfanslist[2].albums && newfanslist[2].albums.length > 0 ? newfanslist[2].albums[0].photo : "",
                memo: newfanslist[2].memo
            } : deffan;
            // 主图展示
            html.push("<div class='xfxdtu mtb5' name='fansshow'> <dl class='xfxnr1' tip='" + newfan1.id + "'>");
            html.push("<dt><img class='lazy' data-original='" + getImageUrl(newfan1.photo, 675, 675) + "' /></dt>");
            html.push("<dd class='xfxdtubt'><a>" + newfan1.memo + "</a></dd>");
            html.push("</dl></div>");
            html.push("<div class='xfxxtu mtb5'  name='fansshow'>");
            html.push("<dl class='xfxnr1' tip='" + newfan2.id + "'> <dt><img class='lazy' data-original='" + getImageUrl(newfan2.photo, 330, 330) + "' /></dt><dd class='xfxdtubt xfxdtubt1'><a>" + newfan2.memo + "</a></dd></dl>");
            html.push("<dl class='xfxnr1 ptop5' tip='" + newfan3.id + "'><dt><img class='lazy' data-original='" + getImageUrl(newfan3.photo, 330, 330) + "' /></dt><dd class='xfxdtubt xfxdtubt1'><a>" + newfan3.memo + "</a></dd></dl>");
            html.push("</div>");
            html.push("<div style='clear: both;'></div>");

            html.push("<div class='mtb5'>");
            html.push("<p class='zxandzrbt'>最新和最热门</p>");
            html.push("<div id='newfanslistdiv' class='horizontalScroll'>");
            html.push("<div class='zxandzr' name='fansshow'>");
            html.push("<dl class='xfxnr1 ptop5 mleft10'><dt><img class='lazy' data-original='../../images/zxtu1.jpg' /></dt></dl>");

            // 最热星粉秀
            $.each(newfanslist, function (i, item) {
                var pic = (item.albums && item.albums.length > 0) ? item.albums[0].photo : ""
                html.push("<dl tip='" + item.id + "' class='xfxnr1 ptop5'><dt><img class='lazy' data-original='" + getImageUrl(pic, 72, 72) + "' /></dt><dd class='xfxdtubt xfxdtubt1'><a>" + item.memo + ".</a></dd></dl>");
            });

            html.push("<div style='clear: both;'></div><p class='zrfxs mbbottom'></p>");
            html.push("</div>");
            html.push("</div>");

            html.push("<div id='hotfanslistdiv' class='horizontalScroll'>");
            html.push("<div class='zxandzr' name='fansshow'>");
            html.push("<dl class='xfxnr1 ptop5 mleft10'> <dt><img class='lazy' data-original='../../images/zrtu1.jpg' /></dt></dl>");

            // 最新星粉秀
            $.each(hotfanslist, function (i, item) {
                var pic = (item.albums && item.albums.length > 0) ? item.albums[0].photo : ""
                html.push("<dl tip='" + item.id + "' class='xfxnr1 ptop5'><dt><img class='lazy' data-original='" + getImageUrl(pic, 72, 72) + "' /></dt><dd class='xfxdtubt xfxdtubt1'><a>" + item.memo + ".</a></dd></dl>");
            });

            html.push("<div style='clear: both;'></div><p class='zrfxs mbbottom'></p>");
            html.push("</div></div>");


            html.push("</div>");
            $("#fanslistdiv").html(html.join(""));
            $(".zxandzr dl").width($(window).width() * 0.225);
            $("#hotfanslistdiv .zxandzr").width($(window).width() / 4 * (hotfanslist.length + 1));
            $("#newfanslistdiv .zxandzr").width($(window).width() / 4 * (newfanslist.length + 1));

            $('img.lazy').lazyload({
                placeholder: "../../images/grey.gif",
                event: "scroll",
                threshold: 100,
                container: $(".main"),
                failure_limit: 10
            });
        },

        // 获取兑换列表
        loadgoods: function () {
            var postdata = {index: 1, size: 5, search: {}};
            var activeli = $('#coinRangelist li[class=goldcolor]');
            if (activeli) {
                postdata.search["count"] = activeli.attr("tip");
            }

            $.ajax({
                headers: {'Content-Type': 'application/json'},
                type: "POST",
                url: CONFIG_MANAGER.RequstUrl + "v1/goods/search/pentacles",
                data: JSON.stringify(postdata),
            }).done(function (res) {
                var response = JSON.parse(res);
                if (response.count == 0) {
                    $("#nodatamessge").show();
                } else {
                    $("#nodatamessge").hide();
                }
                var list = response.data.data;
                var html = [];
                for (var i = 0; i < list.length; i++) {
                    for (var j = 0; j < list[i].lst_sku.length; j++) {
                        var goodsitem = list[i].lst_sku[j];
                        html.push("<li class='syxhd' tip='" + goodsitem.sku_id + "'><dl>");
                        html.push("<dt><img class='lazy' data-original='" + getImageUrl(goodsitem.logo, 496, 466) + "' src='../../images/place/496x466.png''></dt>");
                        html.push("<dd>" + goodsitem.name + goodsitem.specs + "</dd>");
                        if (goodsitem.Is_coin == 1) {
                            html.push("<dd class='spjge mtop5'><span class='jinbi'><b><img src='../../images/jbtub.jpg'></b>" + goodsitem.coin + "</span>+<span class='money'>￥" + goodsitem.sku_actprice + "</span></dd>");
                        } else {
                            html.push("<dd class='xhmony'>￥" + goodsitem.shop_price + "</dd>");
                        }
                        html.push("</dl></li>");
                        if (j == 9) {
                            break;
                        }
                    }
                }
                $("#goodslist").html(html.join(""));
                $('img.lazy').lazyload({
                    placeholder: "../../images/grey.gif",
                    event: "scroll",
                    threshold: 100,
                    container: $("#goodslist"),
                    failure_limit: 10
                });
            });
        },

        // 判断显示置顶图标
        isDisplayTopIcon: function (y) {
            var top = _main.scrollTop();
            if (top > _contentheight / 2) {
                $("#gotop").show();
            } else {
                $("#gotop").hide();
            }
            ;
        },
    };

    var _coinlistPage = new coinlistPage();
}
